package myexchange

import org.springframework.transaction.annotation.Transactional;

class GameService {

    static transactional = false

	CardService cardService
	TurnService turnService
	
	public Game getActiveGame(){
		def games = Game.all
		if(games){
			return games.first()
		}else{
			return null
		}
	}
	
	@Transactional
	public Game startGame(){
		//TODO create support for more than one game
		Game game = new Game()
		game.players = Player.all
		game.save(failOnError: true);
		
		//TODO distribute cards to the users
		game.activeCards = []
		game.usedCards = []
		game.unusedCards = cardService.setupCards(Player.count());

		Card card
		Player.list().each {player ->
			(1..5).each{it ->
				card = cardService.getNextCard() 
				player.addToCards(card)
			}
		}
		return game
	}
	
	public void addHistory(String note, Player player){
		new History([
			note:note, 
			createTime:new Date(), 
			player:player,
			turn:turnService.getCurrentTurn(),
			]).save(failOnError: true)
	}
	
}
